<?php
namespace app\api\model;
use think\Model;
use think\Db;

class Team extends Model{
    protected $type = [
        'id'            =>'integer',
        'operator_id'            =>'integer',
        'type'            =>'integer',
        'branch_id'    =>  'integer',  
        'category_id'    =>  'integer',
        'is_review'    =>  'integer' 
  
    ];   
    
    //多表关联    
    public function operator(){
        return $this->hasOne('manager','id','operator_id');
    }
    public function branch(){
        return $this->hasOne('category','id','branch_id');
    }
    public function category(){
        return $this->hasOne('category','id','category_id');
    } 
    public function incomes(){
        return $this->hasMany('TeamIncome','parent_id','id');
    } 
    public function outlays(){
        return $this->hasMany('TeamOutlay','parent_id','id');
    }
    public function teamList($filter = null){        
        $where = [
            'type' => $filter['type']
        ];
        $whereOr=[];
        $cwhere="";
        $iwhere = ['type' => $filter['type']];
        $owhere= ['type' => $filter['type']];
        $page = 1;
        $pageCount = 10;
        $type = $filter['type'];
        
        if(!empty($filter)){
            //指定id查询
            if(!empty($filter['id'])){
                $where['id'] = $filter['id'];
            }           
            if(!empty($filter['is_departure']) && $filter['is_departure'] == 1){
                //按出发日期查询
                if(!empty($filter['start_date']) && !empty($filter['end_date'])){
                    $where['start_date'] = [['>= time',$filter['start_date']],['<= time',$filter['end_date']]];
                }else{
                    if(!empty($filter['start_date'])){
                        $where['start_date'] = ['>= time',$filter['start_date']];  
                    }
                    if(!empty($filter['end_date'])){
                        $where['start_date'] = ['<= time',$filter['end_date']];  
                    }
                }                
            }else{
                //按录入日期查询
                if(!empty($filter['start_date']) && !empty($filter['end_date'])){
                    $where['create_time'] = [['>= time',$filter['start_date']],['<= time',$filter['end_date']]];
                }else{
                    if(!empty($filter['start_date'])){
                        $where['create_time'] = ['>= time',$filter['start_date']];  
                    }
                    if(!empty($filter['end_date'])){
                        $where['create_time'] = ['<= time',$filter['end_date']];  
                    }
                }  
            }
            //查询团号
            if(!empty($filter['sn'])){
                $where['sn'] = ['like',"%{$filter['sn']}%"];
            }
            //模糊查询           
            if(!empty($filter['keyword'])){
                $where['title'] = ['like',"%{$filter['keyword']}%"];               
            }
            //页码            
            $page = !empty($filter['page']) ? $filter['page'] : $page;
            $pageCount = !empty($filter['page_count']) ? $filter['page_count'] : $pageCount;
            //按客户查询
            if(!empty($filter['client_id'])){
                $cwhere="id in (select parent_id from lt_team_income where type={$filter['type']} and client_id ={$filter['client_id']}) ";
            }
            //按所属查询
            if(!empty($filter['category_id'])){
                $where['category_id'] = $filter['category_id'];
            }
            //按部门查询
            if(!empty($filter['branch_id'])){
                $where['branch_id'] = $filter['branch_id'];
            }
            //按业务员查询
            if(!empty($filter['salesman_id'])){
                $iwhere['salesman_id'] = $filter['salesman_id'];
            }
            //按操作员查询
            if(!empty($filter['operator_id'])){
                $where['operator_id'] = $filter['operator_id'];
                $whereOr="find_in_set({$filter['operator_id']},be_sales)";
            }
        }
        
        $datas = $this->where($cwhere)->where($where)->whereOr($whereOr)->with([
            'incomes'=>function($request)use($iwhere){$request->order('id', 'asc')->where($iwhere)
                ->with(['receipts'=>function($request)use($iwhere){$request->where('type',$iwhere['type']);},'guest','client','salesman']);},
            'outlays'=>function($request)use($owhere){$request->order('id', 'asc')->where($owhere)
                ->with(['payments'=>function($request)use($owhere){$request->where('type',$owhere['type']);}, 'supplier']);},               
                "category"=>'category',
                "branch"=>'branch',
                'operator'=>'operator'
            ])->page("$page,$pageCount")->order('start_date', 'desc')->select();                       
            foreach ($datas as &$v) {  
                $monthly = Db::name("monthly")->where("year_month",date("Y-m",strtotime($v['start_date'])))->find();  
                if($monthly){
                $v['is_monthly'] =  1;
                }else{
                $v['is_monthly'] =  0;
                }
               
                $review = 0;
                $v['receipt_review']=0;
                $v['payment_review']=0;
                //应收
                foreach ($v['incomes'] as $i) {
                   if($i['is_review']==1){
                    $review = 1;
                   }
                   foreach ($i['receipts'] as $r) {
                        $v['receipt_review']=0;
                        if($r['is_review']){
                            $v['receipt_review']=1;
                        }           
                    }
                  
                }
                //应付
                foreach ($v['outlays'] as $i) {
                    if($i['is_review']==1){
                        $review = 1;                    
                    }
                    foreach ($i['payments'] as $r) {
                        $v['payment_review']=0;
                        if($r['is_review']){
                            $v['payment_review']=1;
                        }           
                    }
                   
                }              
                $v['review'] = $review;
            }

        $dataCount =  $this->where($cwhere)->where($where)->whereOr($whereOr)->count();       
        $datalist = array(
            'datas' => $datas,            
            'dataCount' => $dataCount
        );
        return $datalist;      
    }

    public function teamInfo($filter = null){        
        $where = [
            'id' => $filter['id'],
            'type' => $filter['type']
        ];
        $iwhere = [           
            'type' => $filter['type']
        ];
        $owhere = [          
            'type' => $filter['type']
        ];
        
        $datas = $this->where($where)->with([
            'incomes'=>function($request)use($iwhere){$request->where($iwhere)
                ->with(['receipts'=>function($request)use($iwhere){$request->where('type',$iwhere['type']);}]);},
            'outlays'=>function($request)use($owhere){$request->where($owhere)
                ->with(['payments'=>function($request)use($owhere){$request->where('type',$owhere['type']);}]);}
            ])->select();     
        return $datas;      
    }
    public function teamExcel($filter = null){        
        $where = [
            'type' => $filter['type']
        ];
        $iwhere = ['type' => $filter['type']];
        $owhere= ['type' => $filter['type']];
        $page = 1;
        $pageCount = 10;
        $type = $filter['type'];
        
        if(!empty($filter)){
            //指定id查询
            if(!empty($filter['id'])){
                $where['id'] = $filter['id'];
            }           
            if(!empty($filter['is_departure']) && $filter['is_departure'] == 1){
                //按出发日期查询
                if(!empty($filter['start_date']) && !empty($filter['end_date'])){
                    $where['start_date'] = [['>= time',$filter['start_date']],['<= time',$filter['end_date']]];
                }else{
                    if(!empty($filter['start_date'])){
                        $where['start_date'] = ['>= time',$filter['start_date']];  
                    }
                    if(!empty($filter['end_date'])){
                        $where['start_date'] = ['<= time',$filter['end_date']];  
                    }
                }                
            }else{
                //按录入日期查询
                if(!empty($filter['start_date']) && !empty($filter['end_date'])){
                    $where['create_time'] = [['>= time',$filter['start_date']],['<= time',$filter['end_date']]];
                }else{
                    if(!empty($filter['start_date'])){
                        $where['create_time'] = ['>= time',$filter['start_date']];  
                    }
                    if(!empty($filter['end_date'])){
                        $where['create_time'] = ['<= time',$filter['end_date']];  
                    }
                }  
            }
            //查询团号
            if(!empty($filter['sn'])){
                $where['sn'] = ['like',"%{$filter['sn']}%"];
            }
            //模糊查询           
            if(!empty($filter['keyword'])){
                $where['title'] = ['like',"%{$filter['keyword']}%"];               
            }
            //页码            
            $page = !empty($filter['page']) ? $filter['page'] : $page;
            $pageCount = !empty($filter['page_count']) ? $filter['page_count'] : $pageCount;
            //按客户查询
            if(!empty($filter['client_id'])){
                $iwhere['client_id'] = $filter['client_id'];
            }
            //按所属查询
            if(!empty($filter['category_id'])){
                $where['category_id'] = $filter['category_id'];
            }
            //按部门查询
            if(!empty($filter['branch_id'])){
                $where['branch_id'] = $filter['branch_id'];
            }
            //按业务员查询
            if(!empty($filter['salesman_id'])){
                $iwhere['salesman_id'] = $filter['salesman_id'];
            }
            //按操作员查询
            if(!empty($filter['operator_id'])){
                $where['operator_id'] = $filter['operator_id'];
            }
        }
        
        $datas = $this->where($where)->order('id', 'desc')->select();            
            foreach ($datas as &$item) {                  
                $incomes = Db::name("team_income")->where(['type'=>$type,'parent_id'=>$item['id']])->select();  
                $outlays = Db::name("team_outlay")->where(['type'=>$type,'parent_id'=>$item['id']])->select();  
                $receivable=0;
                $payable=0;     
                $received=0;   
                $pay=0;        
                //应收
                foreach ($incomes as $v) {
                    $receivable+=$v['sell_price']*$v['num'];     
                    //已收款               
                    $receipt = Db::name("receipt")->where(['type'=>$type,'income_id'=>$v['id']])->select();  
                    foreach ($receipt as $v) {
                        $received+=$v['money'];
                    }
                }
                //应付
                foreach ($outlays as $v) {
                    $payable = $v['cost_price']*$v['num'];
                    //未收款
                    $payment = Db::name("payment")->where(['type'=>$type,'outlay_id'=>$v['id']])->select();  
                    foreach ($payment as $v) {
                        $pay+=$v['money'];
                    }
                }


                $item['receivable'] = $receivable;
                $item['payable'] = $payable;
                $item['received'] = $received;
                $item['pay'] = $pay;
            }       
        return  $datas;      
    }

    public function allList($filter = null){        
        $where = [
            'type' => $filter['type']
        ];
        $cwhere="";
        $iwhere = ['type' => $filter['type']];
        $owhere= ['type' => $filter['type']];
        $page = 1;
        $pageCount = 10;
        $type = $filter['type'];
        
        if(!empty($filter)){
            //指定id查询
            if(!empty($filter['id'])){
                $where['id'] = $filter['id'];
            }           
            if(!empty($filter['is_departure']) && $filter['is_departure'] == 1){
                //按出发日期查询
                if(!empty($filter['start_date']) && !empty($filter['end_date'])){
                    $where['start_date'] = [['>= time',$filter['start_date']],['<= time',$filter['end_date']]];
                }else{
                    if(!empty($filter['start_date'])){
                        $where['start_date'] = ['>= time',$filter['start_date']];  
                    }
                    if(!empty($filter['end_date'])){
                        $where['start_date'] = ['<= time',$filter['end_date']];  
                    }
                }                
            }else{
                //按录入日期查询
                if(!empty($filter['start_date']) && !empty($filter['end_date'])){
                    $where['create_time'] = [['>= time',$filter['start_date']],['<= time',$filter['end_date']]];
                }else{
                    if(!empty($filter['start_date'])){
                        $where['create_time'] = ['>= time',$filter['start_date']];  
                    }
                    if(!empty($filter['end_date'])){
                        $where['create_time'] = ['<= time',$filter['end_date']];  
                    }
                }  
            }
            //查询团号
            if(!empty($filter['sn'])){
                $where['sn'] = ['like',"%{$filter['sn']}%"];
            }
            //模糊查询           
            if(!empty($filter['keyword'])){
                $where['title'] = ['like',"%{$filter['keyword']}%"];               
            }
            //页码            
            $page = !empty($filter['page']) ? $filter['page'] : $page;
            $pageCount = !empty($filter['page_count']) ? $filter['page_count'] : $pageCount;
            //按客户查询
            if(!empty($filter['client_id'])){
                $cwhere="id in (select parent_id from lt_team_income where type={$filter['type']} and client_id ={$filter['client_id']}) ";
            }
            //按所属查询
            if(!empty($filter['category_id'])){
                $where['category_id'] = $filter['category_id'];
            }
            //按部门查询
            if(!empty($filter['branch_id'])){
                $where['branch_id'] = $filter['branch_id'];
            }
            //按业务员查询
            if(!empty($filter['salesman_id'])){
                $iwhere['salesman_id'] = $filter['salesman_id'];
            }
            //按操作员查询
            if(!empty($filter['operator_id'])){
                $where['operator_id'] = $filter['operator_id'];
            }
        }
        
        $datas = $this->where($cwhere)->where($where)->with([
            'incomes'=>function($request)use($iwhere){$request->where($iwhere)
                ->with(['receipts'=>function($request)use($iwhere){$request->where('type',$iwhere['type']);},'guest','client','salesman']);},
            'outlays'=>function($request)use($owhere){$request->where($owhere)
                ->with(['payments'=>function($request)use($owhere){$request->where('type',$owhere['type']);},'supplier']);},
                "category"=>'category',
                "branch"=>'branch',
                'operator'=>'operator'
            ])->order('start_date', 'desc')->select();            
            foreach ($datas as &$v) {  
                   $monthly = Db::name("monthly")->where("year_month",date("Y-m",strtotime($v['start_date'])))->find();  
                   if($monthly){
                    $v['is_monthly'] =  1;
                   }else{
                    $v['is_monthly'] =  0;
                   }
                $review = 0;
                //应收
                foreach ($v['incomes'] as $i) {
                   if($i['is_review']==1){
                    $review = 1;
                   }
                }
                //应付
                foreach ($v['outlays'] as $i) {
                    if($i['is_review']==1){
                        $review = 1;                    
                    }
                }
                $v['review'] = $review;
            } 
        
        return $datas;      
    }
}